
# 约定书编码表
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django.core.cache import cache
from apps.config.serializers import Menu_serializer
from apps.business.models import Type_coderule_model,Business_type_model
from django.db import transaction
def conrulecode_view(request):
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request,'conrulecode/list.html', {'data': menu_obj.data})

# 添加规则页面
def rules_insert_view(request):
    return render(request,'conrulecode/insert.html')

# 添加动作
@transaction.atomic
def rules_insert(request):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50010201' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    type_id = request.POST.get('type')
    rule_year = request.POST.get('rule_year')
    rule_perfix = request.POST.get('rule_perfix')
    rule_suffix = request.POST.get('rule_suffix')
    remark = request.POST.get('remark_describe')
    # 这里判断年份下type是否存在，如果存在，则不允许创建，要求进行修改
    try:
        obj=Type_coderule_model.objects.filter(type_rule_id=type_id)
        if len(obj)>0:
            return JsonResponse({'code': 204, 'msg': '已拥有添加年份下的规则，请直接修改规则！'})
    except Exception as a:
        transaction.savepoint_rollback(spoint_1) # 可以回滚到指定的保存点
        return JsonResponse({'code': 203, 'msg': '未知错误！'})
    try:
        Type_coderule_model.objects.create(rule_perfix=rule_perfix,rule_suffix=rule_suffix,rule_year=rule_year,
                                           remark_describe=remark,type_rule_id=type_id)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# 查询所有
def rules_list(request):
    try:
        rule_list = Type_coderule_model.objects.all()
        rule_count =Type_coderule_model.objects.count()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '查询出错！'})
    list_data = []
    for i in rule_list:
        dict = {}
        dict['id'] = i.id
        dict['rule_year'] = i.rule_year
        dict['rule_nownum'] = i.rule_nownum
        dict['rule_begin'] = i.rule_begin
        dict['rule_suffix'] =i.rule_suffix
        dict['rule_perfix'] = i.rule_perfix
        dict['type_id'] = i.type_rule_id
        dict['type_name'] = list(Business_type_model.objects.values_list('type_name',flat=True).filter(id=i.type_rule_id))
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict['remark_describe'] = i.remark_describe
        list_data.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list_data, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': rule_count, 'data': res}
    return JsonResponse(Result)

# 修改页面
def rules_edit_view(request):
    return render(request, 'conrulecode/edit.html')

# 修改动作
@transaction.atomic
def rules_edit(request,id):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50010202' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    rule_perfix = request.POST.get('rule_perfix')
    rule_suffix = request.POST.get('rule_suffix')
    rule_begin = request.POST.get('rule_begin')
    rule_nownum = request.POST.get('rule_nownum')
    remark = request.POST.get('remark_describe')
    now_number = Type_coderule_model.objects.get(pk=id).rule_nownum
    if rule_nownum !=now_number:
        new_number = 0
        try:
            Type_coderule_model.objects.filter(pk=id).update(rule_suffix=rule_suffix,rule_perfix=rule_perfix,rule_nownum=new_number,remark_describe=remark)
        except Exception as e:
            transaction.savepoint_rollback(spoint_1) # 可以回滚到指定的保存点
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    else:
        try:
            Type_coderule_model.objects.filter(pk=id).update(rule_suffix=rule_suffix,rule_perfix=rule_perfix,rule_nownum=rule_nownum,remark_describe=remark)
        except Exception as e:
            transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code': 0, 'msg': '修改成功！'})

# 删除动作
@transaction.atomic
def rules_del(request,id):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50010203' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        Type_coderule_model.objects.get(pk=id).delete()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 202, 'msg': 'rulecode删除模块出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '删除成功！'})

# 查询
def rules_search(request):
    name = request.GET.get('searchname')
    try:
        if len(name) == 0:
            rule_list = Type_coderule_model.objects.filter()
        else:
            # 支持业务类型/前缀
            rule_list = Type_coderule_model.objects.filter(
                Q(type_rule__type_name__contains=name) | Q(rule_perfix__contains=name))
        count = len(list(rule_list))
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'code编码查询模块出现问题，请联系管理员！'})
    list_data = []
    for i in rule_list:
        dict = {}
        dict['id'] = i.id
        dict['rule_year'] = i.rule_year
        dict['rule_nownum'] = i.rule_nownum
        dict['rule_begin'] = i.rule_begin
        dict['rule_suffix'] = i.rule_suffix
        dict['rule_perfix'] = i.rule_perfix
        dict['type_id'] = i.type_rule_id
        dict['type_name'] = list(
            Business_type_model.objects.values_list('type_name', flat=True).filter(id=i.type_rule_id))
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict['remark_describe'] = i.remark_describe
        list_data.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list_data, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': count, 'data': res}
    return JsonResponse(Result)

# 年度变更操作
@transaction.atomic
def rules_dateset(request):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50010204' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    new_date=request.POST.get('date')
    try:
        Type_coderule_model.objects.all().update(rule_year=new_date,rule_nownum=0)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 201, 'msg': 'code年度处理模块出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '更新年度成功！'})